package org.genntii.smcommon.config;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class MQConfig {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void initRabbitReturnCallback() {

        // 设置RabbitMQ 消息发送者MessageReturn确认
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.debug("监听到 MessageReturn");
            log.debug("交换机: {}, Key: {}, 消息: {}, replyCode: {}, replyText: {}", returnedMessage.getExchange(), returnedMessage.getRoutingKey(), returnedMessage.getMessage(), returnedMessage.getReplyCode(), returnedMessage.getReplyText());
        });

        // 设置RabbitMQ 消息消费者确认返回机制
        rabbitTemplate.setConfirmCallback(((correlationData, ack, cause) -> {
            if(ack) {
                log.debug("消息发送成功, MessageID: {}", correlationData.getId());
            }
            else {
                log.debug("消息发送失败, 原因: {}, MessageID: {}", cause, correlationData.getId());
            }
        }));
    }
}
